package com.szh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.domain.OrderInfo;
import com.szh.domain.Product;
import com.szh.enums.OrderStatus;
import com.szh.mapper.OrderInfoMapper;
import com.szh.service.OrderInfoService;
import com.szh.service.ProductService;
import com.szh.utils.OrderNoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderInfoServiceImpl.class);

    @Autowired
    private ProductService productService;

    /**
     * 根据订单号查询订单状态
     * @param orderNo 订单号
     * @return 订单状态
     */
    @Override
    public String queryOrderStatus(String orderNo) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo orderInfo = this.getOne(queryWrapper);
        if (null == orderInfo) {
            return null;
        }
        return orderInfo.getOrderStatus();
    }

    /**
     * 根据商品id生成订单
     * @param productId 商品id
     * @param paymentType 支付类型
     * @return OrderInfo
     */
    @Override
    public OrderInfo createOrderByProductId(Long productId, String paymentType) {
        //查找已存在但未支付的订单
        OrderInfo orderInfo = this.getNoPayOrderByProductId(productId, paymentType);
        if (null != orderInfo) {
            return orderInfo;
        }
        //获取商品信息
        Product product = productService.getById(productId);
        orderInfo = new OrderInfo();
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo());
        orderInfo.setProductId(productId);
        orderInfo.setTitle(product.getTitle());
        orderInfo.setTotalFee(product.getPrice());
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
        orderInfo.setPaymentType(paymentType);
        //将生成的订单保存到数据库
        this.save(orderInfo);
        return orderInfo;
    }

    /**
     * 根据订单号获取订单
     * @param outTradeNo 订单号
     * @return OrderInfo
     */
    @Override
    public OrderInfo getOrderByOrderNo(String outTradeNo) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", outTradeNo);
        OrderInfo orderInfo = this.getOne(queryWrapper);
        return orderInfo;
    }

    /**
     * 根据订单号更新订单状态，支付成功之后，更新订单状态为支付成功
     * @param orderNo 订单号
     * @param orderStatus 订单状态
     */
    @Override
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {
        LOGGER.info("更新订单状态 ===> {}", orderStatus.getType());
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(orderStatus.getType());
        this.update(orderInfo, queryWrapper);
    }

    /**
     * 查询创建超过minutes分钟、并且未支付的订单
     * @param minutes 分钟
     * @param paymentType 支付类型
     * @return orderInfoList
     */
    @Override
    public List<OrderInfo> getNoPayOrderByDuration(int minutes, String paymentType) {
        //now()获取当前时间，minus减去传入的时间，计算时间差
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", OrderStatus.NOTPAY.getType());
        queryWrapper.eq("payment_type", paymentType);
        queryWrapper.le("create_time", instant);
        List<OrderInfo> orderInfoList = this.list(queryWrapper);
        return orderInfoList;
    }

    /**
     * 查询订单列表，按照创建时间倒序
     * @return List<OrderInfo>
     */
    @Override
    public List<OrderInfo> listOrderByCreateTimeDesc() {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(OrderInfo::getCreateTime);
        return this.list(queryWrapper);
    }

    /**
     * 存储订单支付二维码
     * @param orderNo 订单号
     * @param codeUrl 二维码链接
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCodeUrl(codeUrl);
        this.update(orderInfo, queryWrapper);
    }

    /**
     * 查找已存在但未支付的订单，防止重复创建订单对象
     * @param productId 商品id
     * @param paymentType 支付类型
     * @return OrderInfo
     */
    private OrderInfo getNoPayOrderByProductId(Long productId, String paymentType) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getProductId, productId);
        queryWrapper.eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType());
        queryWrapper.eq(OrderInfo::getPaymentType, paymentType);
        return this.getOne(queryWrapper);
    }
}
